package com.ddl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ddl.common.enums.ErrorCode;
import com.ddl.common.exception.BusinessException;
import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.dao.UserFriendMapper;
import com.ddl.dao.UserMapper;
import com.ddl.pojo.MsgInfo;
import com.ddl.pojo.User;
import com.ddl.pojo.UserFriend;
import com.ddl.service.IUserFriendService;
import com.ddl.util.DateUtil;
import com.ddl.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/12/1
 */
@Service
public class UserFriendServiceImpl implements IUserFriendService {
    private final static Logger logger = LoggerFactory.getLogger(UserFriendServiceImpl.class);
    @Autowired
    UserFriendMapper userFriendMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IMSingleChatService imSingleChatService;

    /**
     * 添加好友
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel addFriend(String userId, String friendNo) {
        logger.info("添加好友入参userId={},friendNo={}", userId, friendNo);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            User record = new User();
            record.setPhone(friendNo);
            List<User> list = userMapper.selectBySelective(record);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_309);
            }
            User friendUser = list.get(0);
            if (userId.equals(friendUser.getId().toString())) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_316);
            }
            //判断该好友是否之前申请过  如果申请过修改记录 没有则添加
            UserFriend userFriend = new UserFriend();
            userFriend.setUserId(Integer.parseInt(userId));
            userFriend.setFriendId(friendUser.getId());
            List<UserFriend> userFriends = userFriendMapper.selectByRecord(userFriend);
            if (userFriends == null || userFriends.size() <= 0) {
                UserFriend addFriend = new UserFriend();
                addFriend.setUserId(Integer.parseInt(userId));
                addFriend.setFriendId(friendUser.getId());
                addFriend.setStatus(0);//申请
                userFriendMapper.insertSelective(addFriend);
            } else {
                UserFriend updateFriend = userFriends.get(0);
                updateFriend.setStatus(0);
                userFriendMapper.updateByPrimaryKeySelective(updateFriend);
            }
            imSingleChatService.addFriend(userId, friendUser.getId().toString(), 1, "加好友");
        } catch (Exception e) {
            logger.error("添加好友出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    public ResultModel agreeFriend(String userId, String applyUserId, String status) {
        logger.info("同意好友添加入参userId={},applyUserId={}", userId, applyUserId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            UserFriend record = new UserFriend();
            record.setUserId(Integer.parseInt(userId));
            record.setFriendId(Integer.parseInt(applyUserId));
            record.setStatus(0);
            List<UserFriend> list = userFriendMapper.selectByRecord(record);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_310);
            }
            UserFriend userFriend = list.get(0);
            userFriend.setStatus(Integer.parseInt(status));
            userFriendMapper.updateByPrimaryKeySelective(userFriend);
        } catch (Exception e) {
            logger.error("同意好友添加出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    public ResultModel friendList(String userId) {
        logger.info("我的好友列表入参userId={}", userId);
        Map<String, Object> dataMap = new HashMap<>();
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            List<Map<String, Object>> mapList = new ArrayList<>();
            List<UserFriend> list = userFriendMapper.selectFriends(Integer.parseInt(userId));
            if (list != null) {
                for (UserFriend userFriend : list) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("friendUserId", userFriend.getFriendId());
                    User friendUser = userMapper.selectByPrimaryKey(userFriend.getFriendId());
                    map.put("friendUserName", friendUser.getUserName());
                    map.put("imgUrl", friendUser.getHeadImage());
                    mapList.add(map);
                }
            }
            dataMap.put("friendList", mapList);
            resultModel.setData(dataMap);
        } catch (Exception e) {
            logger.error("我的好友列表出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    public ResultModel searchFriend(String mobile) {
        logger.info("搜索好友入参mobile={}", mobile);
        Map<String, Object> dataMap = new HashMap<>();
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            User record = new User();
            record.setPhone(mobile);
            List<User> list = userMapper.selectBySelective(record);
            if (list != null && list.size() > 0) {
                User user = list.get(0);
                dataMap.put("userName", user.getUserName());
                dataMap.put("imageUrl", user.getHeadImage());
                dataMap.put("userId", user.getId());
            }
            resultModel.setData(dataMap);
        } catch (Exception e) {
            logger.error("我的好友列表出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    public ResultModel newsList(String fromId, String toId) {
        logger.info("我的消息列表入参fromId={},toId={}", fromId, toId);
        Map<String, Object> dataMap = new HashMap<>();
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            String beginTime= String.valueOf(DateUtil.nDayAfter(-3, new Date()).getTime());
            String endTime= String.valueOf(System.currentTimeMillis());
            JSONObject jsonObject = imSingleChatService.querySessionMsg(fromId, toId,beginTime,endTime, 100, 2);
            List<MsgInfo> list=new ArrayList<>();
            if(jsonObject!=null&&jsonObject.get("msgs")!=null) {
                list = JSONArray.parseArray(jsonObject.get("msgs").toString(), MsgInfo.class);
            }
//            JSONObject tojsonObject = imSingleChatService.querySessionMsg(toId, fromId,beginTime, endTime, 100, 2);
//            if(tojsonObject!=null&&jsonObject.get("msgs")!=null) {
//                List<MsgInfo> tolist = JSONArray.parseArray(tojsonObject.get("msgs").toString(), MsgInfo.class);
//                list.addAll(tolist);
//            }
            for(MsgInfo msgInfo:list){
                if(StringUtils.isNotBlank(msgInfo.getBody())) {
                    msgInfo.setBody(JSONObject.parseObject(msgInfo.getBody()).get("msg").toString());
                }
            }
            if(list.size()>0) {
                Collections.sort(list, new Comparator<MsgInfo>() {
                    @Override
                    public int compare(MsgInfo o1, MsgInfo o2) {
                        if(o1.getMsgid()>o2.getMsgid()){
                            return 1;
                        } else{
                            return -1;
                        }
                    }
                });
            }
            dataMap.put("newsList", list);
            resultModel.setData(dataMap);
        } catch (Exception e) {
            logger.error("我的消息列表出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        } return resultModel;
    }

    @Override
    public ResultModel sendMsg(String fromId, String toId, String msg) {
        logger.info("发送消息入参fromId={},toId={},msg={}", fromId, toId,msg);
        Map<String, Object> dataMap = new HashMap<>();
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("msg", msg);
            JSONObject jsonObject = imSingleChatService.sendMsg(fromId, 0, toId, 0, JsonUtil.objectToJson(map));
            logger.info("发送消息返回结果{}", jsonObject);
        } catch (Exception e) {
            logger.error("发送消息出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
}
